package cc.cc4414.cc03.sys.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cc.cc4414.cc03.core.constant.RegexpConsts;
import cc.cc4414.cc03.core.controller.BaseController;
import cc.cc4414.cc03.core.result.ResultEnum;
import cc.cc4414.cc03.core.result.ResultVO;
import cc.cc4414.cc03.sys.entity.User;
import cc.cc4414.cc03.sys.service.IUserService;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author cc
 * @since 2018-12-30
 */
@Validated
@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController {

	@Autowired
	private IUserService iUserService;

	/**
	 * 获取当前登录用户信息
	 * 
	 * @return 用户信息
	 */
	@PostMapping("me")
	public ResultVO<User> me() {
		User user = getUser();
		// 将密码设为空
		user.setPassword(null);
		return new ResultVO<>(user);
	}

	/**
	 * 查询用户名被尝试登录的次数
	 * 
	 * @param username 用户名或手机号
	 * @return 尝试登录的次数
	 */
	@GetMapping("getLoginNumber")
	public ResultVO<Integer> getLoginNumber(
			@Pattern(regexp = RegexpConsts.USERNAME_OR_MOBILE) @RequestParam String username) {
		return new ResultVO<>(iUserService.getLoginNumber(username));
	}

	/**
	 * 生成图形验证码并保存至redis
	 * 
	 * @param visitorId 访客id
	 * @param response
	 */
	@GetMapping("captcha")
	public void captcha(@RequestParam String visitorId, HttpServletResponse response) {
		response.setContentType("image/jpeg");
		try {
			iUserService.createCaptcha(visitorId, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 退出登录
	 * 
	 * @return 是否退出登录成功
	 */
	@PostMapping("logout")
	public ResultVO<Object> logout(Authentication authentication) {
		iUserService.removeToken(authentication);
		return new ResultVO<>(ResultEnum.SUCCESS);
	}

}
